const router = require('koa-router')();

const model = require("../../model/register.js");
const mongoose = require("mongoose");

router.prefix('/register');


// 查
router.get('/get', async ctx => {
    let data
    let page = ctx.request.querystring && ctx.request.querystring.split('=')[1]
    if (page) {
        data = await model.find({}).limit(10).skip(page*10)
    } else {
        data = await model.find({})
    }
    
    send(ctx, data, '获取成功')
})

router.get('/get/:name', async ctx => {
    let data = await model.find({name: ctx.params.name})
       
    if (data[ctx.params.name]) {
        send(ctx, data, `名字${ctx.params.name}获取成功`)
    } else {
        sendError(ctx, data)
    }
})

// 增
router.post('/add', async ctx => {
    const obj = await model.findOne({name: ctx.request.body.name})
    if (obj) {
        sendError(ctx, null, '不能重复添加')
    } else {
        let data = await model.create(ctx.request.body)
        send(ctx, data, '保存成功')
    }
})

// 删
router.get('/delete/:name', async ctx => {
    let data = await model.findOne({name: ctx.params.name}).remove()
    if (data.n > 0) {
        send(ctx, data, '删除成功')
    } else {
        sendError(ctx, data)
    }
})



// 改
// router.put('/', async ctx => {
//     let data = await model.create({})

//     send(ctx,'100')
// })


function send(ctx, data = null, msg = '请求成功', code = 200) {
    ctx.body = {
        data,
        msg,
        code 
    }
}

function sendError(ctx, data = null, msg = '无数据', code = 204) {
    ctx.body = {
        data,
        msg,
        code 
    }
}

module.exports = router;

